﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Security;
using System.Drawing;
using System.IO;

namespace WebChatClient.Controllers
{
    public class LogInController : Controller
    {

        HttpClient client = new HttpClient();
        List<Chatter> ListChatter;


        public LogInController()
        {
            client.BaseAddress = new Uri("http://localhost:63046/");
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            ListChatter = new List<Chatter>();
        }



        //
        // GET: /LogIn/

        public ActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Index(Chatter chatter)
        {

            if (ModelState.IsValid)
            {
                if (IsChatterValid(chatter))
                {
                    FormsAuthentication.SetAuthCookie(chatter.Nick, false);
                    return RedirectToAction("Index", "Home");
                }
                {
                    ModelState.AddModelError("","Invalid username or password");
                }
            }
            return View();
        }


        public bool IsChatterValid(Chatter chatter)
        {
            HttpResponseMessage response = client.GetAsync("api/ChatterAPI").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var products = response.Content.ReadAsAsync<IEnumerable<Chatter>>().Result;
                foreach (var p in products)
                {
                    ListChatter.Add(p);
                }
               
            }
            else
            {
                return false;
            }

            //Compare with each in ListChatter

            for (int i = 0; i < ListChatter.Count; i++)
            {
                if ( (chatter.Nick == ListChatter[i].Nick) && (chatter.Password == ListChatter[i].Password) )
                    return true;
            }
                return false;
        }

    }
}
